﻿// 文件使用MiniExcel源码， 使用时需遵循其 Apache License 2.0
// 修改摘要通知： 删除异步、Task等net2.0中不支持的内容，替换原先C#自带的zip处理方式，改用yacomp 进行解压缩。
using System;
using System.Reflection;

namespace ExcelConfig.Utils
{
    internal static class AttributeExtension
    {
        internal static TAttribute GetAttribute<TAttribute>(
           MemberInfo prop,
           bool isInherit = true) where TAttribute : Attribute
        {
            return AttributeExtension<TAttribute>.GetAttributeValue<TAttribute>(prop, (TAttribute attr) => attr, isInherit);
        }

        internal static bool IsUseAttribute<TAttribute>(PropertyInfo prop)
        {
            return Attribute.GetCustomAttribute(prop, typeof(TAttribute)) != null;
        }

        internal static TValue GetAttributeValue<TAttribute,TValue>(
                MemberInfo prop,
                AttributeExtension<TAttribute>.SelectorD selector,
                bool isInherit = true) where TAttribute : Attribute
        {
            return AttributeExtension<TAttribute>.GetAttributeValue<TValue>(prop, selector, isInherit);
        }
    }
    internal static class AttributeExtension<TAttribute> where TAttribute : Attribute
    {
        public delegate object SelectorD(TAttribute attribute);
        private static TValue GetValueOrDefault<TValue>(
            SelectorD selector, 
            TAttribute attr)
        {
            return attr != null ? (TValue)selector(attr) : default;
        }

        internal static TValue GetAttributeValue<TValue>(
                MemberInfo prop,
                SelectorD selector,
                bool isInherit = true)
        {
            var attr = Attribute.GetCustomAttribute(prop, typeof(TAttribute), isInherit) as TAttribute;
            return GetValueOrDefault<TValue>(selector, attr);
        }
    }
}
